
import uuid

from . import conf
from .models import XMPPAccount
from .boshclient import BOSHClient
from .xmpp import register_account


def get_conversejs_context(context, xmpp_login=False):

    context['CONVERSEJS_ENABLED'] = conf.CONVERSEJS_ENABLED
    # not good implemented, but directly to zh from de, magically
    context['LANGUAGE_CODE'] = 'de'

    if not conf.CONVERSEJS_ENABLED:
        return context

    context.update(conf.get_conversejs_settings())

    user = context.get('user')

    if not xmpp_login or not user.is_active:
        return context

    try:
        xmpp_account = XMPPAccount.objects.get(user=user.pk)
    except XMPPAccount.DoesNotExist:
        jid_domain = conf.CONVERSEJS_AUTO_REGISTER
        if not jid_domain:
            return context

        # In hiquanzi.com the username is actually the email address which is malformed
        parsed_username = user.get_username().replace('@', '.')
        xmpp_jid = parsed_username + u'@' + jid_domain
        xmpp_password = uuid.uuid4().hex # get a random uuid as password

        registered = register_account(xmpp_jid, xmpp_password,
                                      user.get_full_name(), user.email)

        if not registered:
            return context

        login_domain_name = conf.CONVERSEJS_DOMAIN
        if login_domain_name:
            xmpp_jid = xmpp_jid.replace(jid_domain, login_domain_name)
        xmpp_account = XMPPAccount.objects.create(jid=xmpp_jid,
                                                  password=xmpp_password,
                                                  user=user)

    bosh = BOSHClient(xmpp_account.jid, xmpp_account.password,
                      context['CONVERSEJS_BOSH_SERVICE_URL'])
    jid, sid, rid = bosh.get_credentials()
    bosh.close_connection()

    context.update({'jid': jid, 'sid': sid, 'rid': rid})

    return context
